package com.mialab.jwbook.filterdemo2.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "SessionCheckFilter", urlPatterns = { "/*" }, initParams = {
        @WebInitParam(name = "loginPage", value = "login.jsp"),
        @WebInitParam(name = "loginServlet", value = "LoginProcessServlet") })

public class SessionCheckFilter implements Filter {
    // 用于获取初始化参数
    private FilterConfig config;

    public SessionCheckFilter() {
    }

    public void init(FilterConfig fConfig) throws ServletException {
        this.config = fConfig;
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        // 获取初始化参数
        String loginPage = config.getInitParameter("loginPage");
        String loginServlet = config.getInitParameter("loginServlet");
        // 获取会话对象
        HttpSession session = ((HttpServletRequest) request).getSession();
        // 获取请求资源路径（不包含请求参数）
        String requestPath = ((HttpServletRequest) request).getServletPath();

        if (session.getAttribute("user") != null || requestPath.endsWith(loginPage)
                || requestPath.endsWith(loginServlet)) {
            // 如果用户会话域属性user存在，并且请求资源为登录页面和登录处理的Servlet，则“放行”请求
            chain.doFilter(request, response);
        } else {
            // 对请求进行拦截，返回登录页面
            request.setAttribute("tip", "您还未登录，请先登录！");
            request.getRequestDispatcher(loginPage).forward(request, response);
        }
    }

    public void destroy() {
        this.config = null;
    }
}

